import TopNav from "@/components/TopNav/index.vue"

import {
    getAlllist,
    updateCartNum,
    deleteCart,
    addCollection,
    getOrderNumber
} from "../../../api/index"

export default {
    components: {
        TopNav,
    },
    props: {
        fromUserCenter: {}, //是否从用户中心引用了改组件，以隐藏头部
    },
    data() {
        return {
            imgBaseUrl: process.env.VUE_APP_WAREHOUSE_API,
            src: require('../../../assets/test02.jpg'),
            checkedAll: false,
            isCheckedList: [], // 选择后保存列表
            cartList: [], // 丛后台拿到的数据
            sumPrice: "0.00", // 总合计
            totalPiece: 0, // 选择了多少商品
            AllPiece: 0, // 一共多少件商品
        }
    },
    methods: {
        // 获取购物车列表
        handleGetAlllist() {
            this.AllPiece = 0
            this.isCheckedList = []
            this.checkedAll = false
            this.sumPrice = '0.00'
            this.totalPiece = 0
            const loading = this.$loading({
                lock: true,
                text: '正在获取...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            })
            getAlllist().then(res => {
                if (res.data.code === 200) {
                    let result = res.data.result

                    result.forEach(item => {
                        item.isChecked = false
                        if (item.detailVoList) {
                            item.detailVoList.forEach(list => {
                                list.isChecked = false
                                list.sumMoney = (parseInt(list.detaiPrice) * parseInt(list.cosePayCount)).toFixed(2)
                            })
                            this.AllPiece += item.detailVoList.length

                        } else {
                            ++this.AllPiece
                            item.sumMoney = (parseInt(item.price) * parseInt(item.payCount)).toFixed(2)
                        }
                    })
                    this.cartList = result
                } else {
                    this.$message({
                        message: res.data.msg,
                        type: 'warning'
                    })
                }
                loading.close()
            }).catch(err => {
                // this.$message.error("获取购物车列表失败！")
                loading.close()
            })
        },

        // 计数器Change事件
        handleNumberChange(id, num, isList) {
            updateCartNum({
                id: id,
                payCount: num
            }).then(res => {
                if (res.data.code === 200) {
                    this.handleGetAlllist()
                    // if(isList){ // true 课程 false 主系统

                    // }else{

                    //     this.isCheckedList.forEach(item=>{
                    //         if(item.isChecked){

                    //         }
                    //         this.cartList.forEach(list=>{
                    //             list.sumMoney = (parseInt(item.price) * parseInt(item.payCount)).toFixed(2)
                    //         })
                    //     })
                    // }
                } else {

                }
            }).catch(err => {
                // this.$message.error("修改数量失败")
            })
        },

        // 移除购物车
        handleDeleteCart(id, name) {
            this.$confirm('确定将“' + name + '”移除您的购物车吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.httpDeteleCart(id)
            }).catch(() => {
                console.log('点击了取消')
            })

        },

        // 批量移除购物车
        handleSelectDelete() {
            if (this.isCheckedList.length <= 0) {
                this.$message('请选择需要移除购物车的商品')
                return false
            }
            let IdsArr = []
            this.isCheckedList.forEach(item => {
                if (item.detailVoList) {
                    item.detailVoList.forEach(list => {
                        IdsArr.push(list.shoppingCarId)
                    })
                } else {
                    IdsArr.push(item.id)
                }
            })
            this.$confirm('确定将选择的移除您的购物车吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.httpDeteleCart(IdsArr.join(','))

            }).catch(() => {
                console.log('点击了取消')
            })
        },

        // 移除购物车请求
        httpDeteleCart(idArray) {
            const loading = this.$loading({
                lock: true,
                text: '正在移除...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            })
            deleteCart({
                ids: idArray
            }).then(res => {
                if (res.data.code === 200) {
                    this.$message({
                        message: '移除购物车成功',
                        type: 'success'
                    })
                    // 更新列表
                    this.handleGetAlllist()
                } else {
                    this.$message({
                        message: res.data.msg,
                        type: 'warning'
                    })
                }
                loading.close()
            }).catch(err => {
                loading.close()
                // this.$message.error("移除购物车失败！")
            })
        },

        // 多个加入收藏夹
        handelSelectAddCollection() {
            if (this.isCheckedList.length <= 0) {
                this.$message('请选择需要加入收藏夹的商品')
                return false
            }
            let commodityIdArr = []
            this.isCheckedList.forEach(item => {
                if (item.detailVoList) {
                    item.detailVoList.forEach(list => {
                        if (list.courseCollection === false) {
                            commodityIdArr.push({"commodityId": list.commodityId})
                        }
                    })
                } else {
                    if (item.collection === false) {
                        commodityIdArr.push({"commodityId": item.commodityId})
                    }
                }

            })
            if (commodityIdArr.length < 1) {
                this.$message('已经加入收藏了，请勿反复添加')
                return false
            }
            const loading = this.$loading({
                lock: true,
                text: '正在加入收藏夹...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            })

            addCollection(commodityIdArr).then(res => {
                if (res.data.code === 200) {
                    this.$message({
                        message: '加入成功',
                        type: 'success'
                    })
                    // 重新请求
                    this.handleGetAlllist()
                } else {
                    this.$message(res.data.msg)
                }
                loading.close()
            }).catch(err => {
                loading.close()
                // this.$message.error("加入收藏夹失败！")
            })
        },

        // 单个加入收藏夹
        handleSingleAddCollection(id) {
            let result = [{"commodityId": id}]
            const loading = this.$loading({
                lock: true,
                text: '正在加入收藏夹...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            })
            addCollection(result).then(res => {
                if (res.data.code === 200) {
                    this.$message({
                        message: '加入成功',
                        type: 'success'
                    })
                    // 重新请求
                    this.handleGetAlllist()
                } else {
                    this.$message(res.data.msg)
                }
                loading.close()
            }).catch(err => {
                loading.close()
                // this.$message.error("加入收藏夹失败！")
            })
        },

        // 结算
        handleSettlement() {
            if (this.cartList <= 0) {
                this.$message('购物车里空空如也')
                return false
            }
            if (this.isCheckedList.length <= 0) {
                this.$message('请选择需要结算的商品')
            } else {
                let result = []
                this.isCheckedList.forEach(item => {
                    if (item.detailVoList) {
                        item.detailVoList.forEach(volist => {
                            result.push(volist.shoppingCarId)
                        })
                    } else {
                        result.push(item.id)
                    }
                })
                const loading = this.$loading({
                    lock: true,
                    text: '正在获取...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                })
                getOrderNumber(result.join(',')).then(res => {
                    if (res.data) {
                        this.$router.push({
                            path: '/order',
                            query: {
                                orderNumber: res.data
                            }
                        })
                    } else {
                        this.$message({
                            message: '获取订单号失败，请联系管理员',
                            type: 'warning'
                        })
                    }
                    loading.close()
                }).catch(err => {
                    loading.close()
                    // this.$message.error("获取订单号失败，请联系管理员"+err)
                })
            }
        },

        // 商品单选
        handleCheckChang(val) {
            // 判断是主系统还是课程
            if (val.detailVoList) {
                // 如果是课程 遍历删除没有选中的课程
                let voList = JSON.parse(JSON.stringify(val)) // 深度克隆
                voList.detailVoList = voList.detailVoList.filter(item => item.isChecked === true)
                this.isCheckedList = this.isCheckedList.filter(item => item.id != val.id)
                if (voList.detailVoList.length > 0) {
                    this.isCheckedList.push(voList)
                }
                let checkVolist = this.isCheckedList.find(item => item.id == val.id)
                if (checkVolist) {
                    if (checkVolist.detailVoList.length === val.detailVoList.length) {
                        this.cartList.forEach(item => {
                            if (item.id === val.id) {
                                item.isChecked = true
                            }
                        })
                    } else {
                        this.cartList.forEach(item => {
                            if (item.id === val.id) {
                                item.isChecked = false
                            }
                        })
                    }
                } else {
                    this.isCheckedList = this.isCheckedList.filter(item => item.id != val.id)
                }
            } else {
                // 如果是主系统则直接判断是否为选中状态去操作暂存数组，选中添加，取消选择删除
                if (val.isChecked) {
                    this.isCheckedList.push(val)
                } else {
                    this.isCheckedList = this.isCheckedList.filter(item => item.id != val.id)
                }
            }
            // 清空选中商品数及合计价格状态,重新计算
            this.totalPiece = 0
            this.sumPrice = 0
            let money = 0
            let isAll = 0
            this.isCheckedList.forEach(item => {
                if (item.detailVoList) {
                    this.totalPiece += item.detailVoList.length
                    isAll += item.detailVoList.length
                    item.detailVoList.forEach(list => {
                        money += parseInt(list.sumMoney)
                    })
                } else {
                    ++this.totalPiece
                    ++isAll
                    money += parseInt(item.sumMoney)
                }
            })
            this.sumPrice = money.toFixed(2)
            if (isAll == this.AllPiece) {
                this.checkedAll = true
            } else {
                this.checkedAll = false
            }
        },

        // 全选
        handleCheckAll(all) {
            this.totalPiece = 0
            if (all) {
                this.isCheckedList = this.cartList
                this.sumPrice = 0
                let price = 0
                this.isCheckedList.forEach(item => {
                    if (item.detailVoList) {
                        item.detailVoList.forEach(list => {
                            price += parseInt(list.sumMoney)
                        })
                        this.totalPiece += item.detailVoList.length
                    } else {
                        price += parseInt(item.sumMoney)
                        ++this.totalPiece
                    }

                })
                this.sumPrice = price.toFixed(2)

            } else {
                this.isCheckedList = []
                this.sumPrice = "0.00"
            }
            this.cartList.forEach(item => {
                item.isChecked = all
                if (item.detailVoList) {
                    item.detailVoList.forEach(list => {
                        list.isChecked = all
                    })
                }
            })
            this.typeCheckedAll = all
        },

        // 系统单选
        handleCheckSystem(val) {
            // 判断是主系统还是还是课程，如果是主系统则去为每个课程与分类选择框一直
            if (val.detailVoList) {
                val.detailVoList.forEach(list => {
                    list.isChecked = val.isChecked
                })
            }

            // 如果当前为选择状态则将此条数据保存到暂存数组中，否则删除
            if (val.isChecked) {
                this.isCheckedList.push(val)
                if (val.detailVoList) {
                    this.totalPiece += val.detailVoList.length
                } else {
                    this.totalPiece += 1
                }
            } else {
                this.isCheckedList = this.isCheckedList.filter(item => item.id !== val.id)
                if (val.detailVoList) {
                    this.totalPiece -= val.detailVoList.length
                } else {
                    this.totalPiece -= 1
                }
            }

            // 结算合计
            if (this.isCheckedList.length > 0) {
                let price = 0
                this.isCheckedList.forEach(item => {
                    if (item.detailVoList) {
                        item.detailVoList.forEach(list => {
                            price += parseInt(list.sumMoney)
                        })

                    } else {
                        price += parseInt(item.sumMoney)
                    }
                })
                this.sumPrice = price.toFixed(2)
            } else {
                this.sumPrice = '0.00'
            }

            // 如果暂存数组的长度与后台返回数组的长度一致则为全选按钮打勾
            if (this.isCheckedList.length === this.cartList.length) {
                this.checkedAll = true
            } else {
                this.checkedAll = false
            }
        },

        // 处理选择的暂存数组过滤
        handlefilter() {
            //this.isCheckedList = this.isCheckedList.filter((item,index,arr)=> item.id === arr[index].id)
            console.log(this.isCheckedList)
        }

    },
    created() {
        this.handleGetAlllist()
    }
}
